package Model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.swing.JOptionPane;


import Controller.Tasker;
import Date.ArrangeView;
import Date.Day;
import Events.Alarm;
import Events.Appointment;
import Events.EventParams;
import Events.GenericEvent;
import Events.MoodleEvent;
import Events.Recurrence;
import Events.Reminder;
import Events.Task;
import Events.TypeEvent;

public class DAOEvent {
  /* {src_lang=Java}*/


  public DAOEventToFile dETF;
  private String FILE = "docs\\events.csv";
  public String FILE_INDEX = "docs\\id.id";
  public ArrayList<Index> actualMonth;
  public DAOEvent(DAOEventToFile tasker)
  {
	  this.dETF=tasker;
	  getLastIndex();
	 //daoOI = new DAOObjectIndex(actualMonth);
  }
  public void saveEvent(GenericEvent event) {
	  //Connection con  =  getConecction();
	  try {
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(new File(FILE), true)));	  
		  if(event.getType()<4)
		  {
			  Date d = event.getD_Start();
			  if(event.getType()!=2)
			  {	  
				  d.setHours(event.getT_Start().getHours());
				  d.setMinutes(event.getT_Start().getMinutes());
				  d.setSeconds(event.getT_Start().getSeconds());
			  }
			  String write = dETF.getID()+","+d.getTime()+","+event.getDescription()+","+event.getType()+","+event.getSubject()+",";
			  if(event.getType()==0)
			  {
				  Appointment app = (Appointment)event;
				  d = app.getD_Final();
				  d.setHours(app.getT_Final().getHours());
				  d.setMinutes(app.getT_Final().getMinutes());
				  d.setSeconds(app.getT_Final().getSeconds());
				  if(app.getParams().get("IDME")==null)
					  write+=d.getTime()+",0,0,0,"+((app.getParams().get("Ringtone").equals(""))?"0":app.getParams().get("Ringtone"));
				  else
					  write +=d.getTime()+",0,0,"+app.getParams().get("IDME")+",0";
			  }
			  else if(event.getType()==1)
			  {
				  Alarm al = (Alarm)event;				  
				  write += 0+","+al.getParams().get("Snozee")+ ",0,0,"+((al.getParams().get("Ringtone").equals(""))?"0":al.getParams().get("Ringtone"));
			  }
			  else if(event.getType()==2)
			  {
				  Task tk = (Task)event;
				  write +="0,0,"+tk.getParams().get("Status")+",0,"+((tk.getParams().get("Ringtone").equals(""))?"0":tk.getParams().get("Ringtone"));
			  }
			  else if(event.getType()==3)
			  {
				  MoodleEvent me = (MoodleEvent)event;
				  d = me.getD_Start();
				  d.setHours(me.getT_Start().getHours());
				  d.setMinutes(me.getT_Start().getMinutes());
				  d.setSeconds(me.getT_Start().getSeconds());
				  write +=d.getTime()+",0,0,"+me.getParams().get("IDME")+",0";
			  }
			  out.println(write);
			  event.setIdEvent(dETF.getID());
			  dETF.sumID();
		  }
		  
		  out.close();
	  } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	 }
  }
  public GenericEvent readEvent(int time)
  {
	  GenericEvent event = null;
	  try {
		Class.forName("org.relique.jdbc.csv.CsvDriver");
		// create a connection. The first command line parameter is assumed to
	      //  be the directory in which the .csv files are held
	    Connection conn = DriverManager.getConnection("jdbc:relique:csv:.\\docs\\");

	      // create a Statement object to execute the query with
	    Statement stmt = conn.createStatement();

	      // Select the ID and NAME columns from sample.csv
	    ResultSet results = stmt.executeQuery("SELECT * FROM events WHERE IDEvent='"+time+"'");

	      // dump out the results
	    while (results.next())
	    {
	    	int type = Integer.parseInt(results.getString("Type"));
	    	if(type==0)
	    	{
	    		
	    		event = new Appointment();
	    		event.setIdEvent(Integer.parseInt(results.getString("IDEvent")));
	    		event.setD_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setT_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setDescription(results.getString("Description"));
	    		event.setType(0);
	    		event.setSubject(results.getString("Subject"));
	    		((Appointment)event).setD_Final(new Date(new Long(results.getString("FinalTime"))));
	    		((Appointment)event).setT_Final(new Date(new Long(results.getString("FinalTime"))));
	    		((Appointment)event).getParams().put("Ringtone", results.getString("Ringtone"));
	    		((Appointment)event).setReminder((Reminder)dETF.readRRT(event.getIdEvent(), 1));
	    		
	    		String dat = results.getString("Type2");
	    		if(dat.equals("0"))
	    		{
	    			((Appointment)event).setRecurrence((Recurrence) dETF.readRRT(event.getIdEvent(), 0));
	    			
	    		}
	    		else
	    		{
		    		((Appointment)event).getParams().put("IDME", results.getString("Type2"));
	    		}
	    		
	    	}
	    	else if(type==1)
	    	{
	    		event = new Alarm();
	    		event.setIdEvent(Integer.parseInt(results.getString("IDEvent")));
	    		event.setD_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setT_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setDescription(results.getString("Description"));
	    		event.setType(1);
	    		event.setSubject(results.getString("Subject"));
	    		((Alarm)event).getParams().put("Ringtone", results.getString("Ringtone"));
	    		((Alarm)event).getParams().put("Snooze", results.getString("Snooze"));
	    		((Alarm)event).setRecurrence((Recurrence) dETF.readRRT(event.getIdEvent(), 0));
	    	}
	    	else if(type==2)
	    	{
	    		event = new Task();
	    		event.setIdEvent(Integer.parseInt(results.getString("IDEvent")));
	    		event.setD_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setT_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setDescription(results.getString("Description"));
	    		event.setType(2);
	    		event.setSubject(results.getString("Subject"));
	    		((Task)event).getParams().put("Ringtone", results.getString("Ringtone"));
	    		((Task)event).getParams().put("Status", results.getString("Status"));
	    		((Task)event).setRecurrence((Recurrence) dETF.readRRT(event.getIdEvent(), 0));
	    		((Task)event).setReminder((Reminder) dETF.readRRT(event.getIdEvent(), 1));
	    		
	    	}
	    	else if(type==3)
	    	{
	    		event = new MoodleEvent();
	    		event.setIdEvent(Integer.parseInt(results.getString("IDEvent")));
	    		event.setD_Start(new Date(new Long(results.getString("StartTime"))));
	    		event.setDescription(results.getString("Description"));
	    		event.setType(3);
	    		event.setSubject(results.getString("Subject"));
	    		((MoodleEvent)event).setT_Start(new Date(new Long(results.getString("FinalTime"))));
	    		((MoodleEvent)event).setD_Start(new Date(new Long(results.getString("FinalTime"))));
	    		((MoodleEvent)event).getParams().put("IDME", results.getString("Type2"));
	    		((MoodleEvent)event).setRecurrence((Recurrence) dETF.readRRT(event.getIdEvent(), 0));
	    	}
	    	System.out.println(results);
	    }

	      // clean up
	    results.close();
	    stmt.close();
	    conn.close();
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

      
	  return event;
  }
//  private void saveRecurrence(Recurrence recurrence, Connection state)
//  {
//	  
//  }
//  public ArrayList<GenericEvent> readEvents() {
//  return null;
//  }
//  public Connection getConecction(){
//	  Connection conexion=null;
//	  try {
//		Class.forName("com.mysql.jdbc.Driver");
//		conexion = DriverManager.getConnection("jdbc:mysql://localhost/tasker", "root", "monitores");
//	} catch (ClassNotFoundException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	} catch (SQLException e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
//	  
//	  return conexion;
//  }
	public ArrayList<GenericEvent> getEvents(ArrangeView arrangeView) {
		ArrayList<GenericEvent> ret = new ArrayList<GenericEvent>();
		int view = arrangeView.getView();
		//int view = 1;
		if(view==0)
		{
			//Date d = new Date(arrangeView.getActualYear(), arrangeView.getActualMonth(), arrangeView.getActualDay());
//				//System.out.println(d);
//				ArrayList<GenericEvent> events = new ArrayList<GenericEvent>();
//				Day day = new Day(arrangeView.getActualMonth(), 0, arrangeView.getActualweek(), arrangeView.getActualMonth(), arrangeView.getActualYear(), events);
			for(Index in : arrangeView.getDay())
			{
				Date d = new Date(in.getTime());
//				System.out.println(d.getDate());
				if(d.getDate()==arrangeView.getActualDay())
				{
					GenericEvent ge = readEvent(in.getIndex());
					if(canAddEvent(ge, arrangeView))
						ret.add(ge);
				}
			}
		}
		else if(view==1)
		{
			Calendar cal = Calendar.getInstance();
			cal.set(arrangeView.getActualYear(), arrangeView.getActualMonth(), arrangeView.getActualDay());
			Date d = new Date(arrangeView.getActualYear()-1900, arrangeView.getActualMonth(), arrangeView.getActualDay()-cal.get(Calendar.DAY_OF_WEEK)+1);
			//System.out.println(d);
			Date dfinal = new Date(d.getYear(), d.getMonth(), d.getDate()+7);
//				Date d = new Date();
			//Crea los 7 dias
//			for(int i=0; i<7; i++)
//				ret.add(new Day(d.getDay()+i, 0, arrangeView.getActualweek(), arrangeView.getActualMonth(), arrangeView.getActualYear(), new ArrayList<GenericEvent>()));
			if(d.getMonth()!=dfinal.getMonth())
			{
				int mount = ((d.getMonth()+1)*(d.getYear()+1900));
				for(Index in : (ArrayList<Index>)dETF.getMonth(0, mount))
				{
					Date eventDate = new Date(in.getTime());
					
					if(d.getTime()<eventDate.getTime() && dfinal.getTime()>eventDate.getTime())
					{
						Calendar calen = Calendar.getInstance();
						calen.set(eventDate.getYear(), eventDate.getMonth(), eventDate.getDate());
						//Se le resta -3 porque son 3 del fallo que presenta al sacar el dia y 1 porque el arreglo comieza desde 0
						GenericEvent ge = readEvent(in.getIndex());
						if(canAddEvent(ge, arrangeView))
							ret.add(ge);
					}
				}
				
			}
			for(Index in : arrangeView.getDay())
			{
				Date eventDate = new Date(in.getTime());
				
				if(d.getTime()<eventDate.getTime() && dfinal.getTime()>eventDate.getTime())
				{
					Calendar calen = Calendar.getInstance();
					calen.set(eventDate.getYear(), eventDate.getMonth(), eventDate.getDate());
					//Se le resta -3 porque son 3 del fallo que presenta al sacar el dia y 1 porque el arreglo comieza desde 0
					GenericEvent ge = readEvent(in.getIndex());
					if(canAddEvent(ge, arrangeView))
						ret.add(ge);
				}
			}
			//System.out.println(cal.getFirstDayOfWeek());
		}
		else if(view==2)
		{
			Calendar cal = Calendar.getInstance();
			cal.set(arrangeView.getActualYear(), arrangeView.getActualMonth(), arrangeView.getActualDay());
			
			
			for(Index in : arrangeView.getDay())
			{
				
				Date eventDate = new Date(in.getTime());
//					Calendar event = Calendar.getInstance();
//					event.set(eventDate.getDay(), eventDate.getMonth(), eventDate.getYear());
				GenericEvent ge = readEvent(in.getIndex());
				if(canAddEvent(ge, arrangeView))
					ret.add(ge);
				//System.out.println(event.get(Calendar.DAY_OF_MONTH));
			}
		}
		return ret;
	}
	public boolean canAddEvent(GenericEvent ge, ArrangeView av)
	{
		int select = av.getSelectedEvents();
		if(ge.getType()==0 && ((Appointment)ge).getParams().get("IDME")!=null && !((Appointment)ge).getParams().get("IDME").equals("0") )
		{
			return (Boolean)av.getParams().get("Moodle");
		}
		else 
		{
			if(!(Boolean)av.getParams().get("Normal"))
				return false;
			if(select!=0)
			{
				return (select==1 && ge.getType()==0 | select==2 && ge.getType()==1 | select==3 && ge.getType()==2);
			}
			return true;
		}
		
		
	}
	public void getLastIndex() {
		// TODO Auto-generated method stub
		try {
			BufferedReader bf = new BufferedReader(new FileReader(FILE_INDEX));
			String dato = bf.readLine();
		    dETF.setID(Integer.parseInt(dato));
		    bf.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "File \"id.id\" not found!!", "Error!", JOptionPane.ERROR_MESSAGE);
			//e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "Unexpected format in \"id.id\"!!", "Error!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		}
	}
	public void saveLastIndex()
	{
		try {
			PrintWriter pw = new PrintWriter(FILE_INDEX);
			pw.println(dETF.getID());
		    //dETF.setID(Integer.parseInt(dato)+1);
			pw.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null, "File \"id.id\" not found!!", "Error!", JOptionPane.ERROR_MESSAGE);
			//e.printStackTrace();
		}
	}
	public void updateCalendarEvents(ArrayList<GenericEvent> events2) {
		// TODO Auto-generated method stub
		
	}
}